package com.meng.function.http;

import com.google.gson.JsonObject;
import com.meng.util.Dict;
import org.bukkit.scheduler.BukkitRunnable;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.logging.Level;

/**
 * @author GuMeng
 */
public class HttpDispose extends BukkitRunnable {

    private JsonObject jsonObject;
    private String ip;
    private String url;
    private StringBuilder result = new StringBuilder();

    public HttpDispose(JsonObject jsonObject, String ip, String url) {
        this.jsonObject = jsonObject;
        this.ip = ip;
        this.url = url;
    }

    @Override
    public void run() {
        msgHttpPost();
    }

    public void msgHttpPost(){
        try {
            URL httpUrl = new URL("http://"+ ip + "/" + url);
            System.out.println(httpUrl);
            HttpURLConnection connection = (HttpURLConnection) httpUrl.openConnection();
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            connection.setRequestProperty("Content-Type", "application/json;charset=utf8");
            connection.getOutputStream().write(jsonObject.toString().getBytes(StandardCharsets.UTF_8));
            connection.getOutputStream().flush();
            connection.getOutputStream().close();
            if (connection.getResponseCode() == 200) {
                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
                String line;
                //读一行文字并返回该行字符
                while ((line = in.readLine()) != null) {
                    result.append(line);
                }
                in.close();
            }else{
                Dict.PLUGIN.getLogger().log(Level.WARNING,"服务端连接失败");
            }
            connection.disconnect();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public void start(){
        runTask(Dict.PLUGIN);
    }

    public StringBuilder getResult() {
        return result;
    }


}
